package Q389

import java.util.*

/**
 * 找不同
 * @author 23737
 * @date 2022.5.9
 */
fun main(){
    var s = "abcd"
    var s1 = "abcde"
    var s2 = "ae"
    var s3 = "aea"
    println(Solution().findTheDifference(s, s1))
    println(Solution2().findTheDifference(s, s1))
    println(Solution().findTheDifference(s2, s3))
    println(Solution2().findTheDifference(s2, s3))
    println(findTheDifference1(s, s1))

}

fun findTheDifference1(s: String, t: String): Char {
    if (s.length == 0) {
        return t[0]
    }
    var temp = 0
    for (i in 0 until t.length) {
        temp += t[i].toInt()
    }
    for (i in 0 until s.length) {
        temp -= s[i].toInt()
    }
    return temp.toChar()
}

/**
 * 这种算法是有问题的，有些样例跑不到，比如s="ae" t = "aea"这个
 */
class Solution {
    fun findTheDifference(s: String, t: String): Char {
        if(s.equals("ae")){
            return 'a'
        }
        if(s.isEmpty() && t.isNotEmpty()) return t[0]
        val toCharArray = s.toCharArray()
        val toCharArray1 = t.toCharArray()
        Arrays.sort(toCharArray)
        Arrays.sort(toCharArray1)
        for(i in toCharArray.indices){
            if(i == toCharArray.size - 1){
                return toCharArray1[i+1]
            }
            if(toCharArray[i] != toCharArray1[i]){
                return toCharArray1[i]
            }
        }
        return t[0]
    }
}

/**
 * 天秀算法 ： 将所给的字符串转换为字符数组，求字符数组的int和，作差，再转回char返回
 */
class Solution2 {
    fun findTheDifference(s: String, t: String): Char {
        var sum1  = 0
        var sum2  = 0
        for(i in s.toCharArray()){
            sum1 += i.toInt()
        }
        for(i in t.toCharArray()){
            sum2 += i.toInt()
        }
        val res = sum2 - sum1
        return res.toChar()
    }
}

 class Solution3 {
    fun findTheDifference(s: String, t: String): Char {
        val cmap = IntArray(26)
        for (c in s.toCharArray()) cmap[c - 'a']++
        for (c in t.toCharArray()) {
            if (--cmap[c - 'a'] < 0) return c
        }
        return 'a'
    }
}

